// 该组件为通用数字动画组件，被多个页面复用，已归类到 common 目录
<template>
  <span ref="countRef"></span>
</template>

<script setup lang="ts">
  import { onMounted, ref, watch } from 'vue'
  import { CountUp } from 'countup.js'

  const props = defineProps({
    end: {
      type: Number,
      required: true,
    },
    options: {
      type: Object,
      default: () => ({}),
      required: false,
    },
  })

  const countRef = ref<HTMLElement | null>(null)
  const countUp = ref<CountUp | null>(null)
  onMounted(() => {
    if (!countRef.value) return
    countUp.value = new CountUp(countRef.value, props.end, props.options)
    if (countUp.value?.error) {
      console.error(countUp.value?.error)
      return
    }
    countUp.value?.start()
  })

  watch(
    () => props.end,
    newVal => {
      if (countUp.value) {
        countUp.value.update(newVal)
      }
    }
  )
</script>
